var createError = require('http-errors');
var express = require('express');
// const router = express.Router();

var path = require('path');
var cookieParser = require('cookie-parser');
var session = require("express-session")({
  secret: 'keyboard cat',
  cookie: {maxAge:800000}
});
var iosession = require("express-socket.io-session")(session);
const Chatmes = require("./routes/chatmes");
const date = require("./public/javascripts/date");

var logger = require('morgan');
var sassMiddleware = require('node-sass-middleware');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();
//app~server~io(socket.io)
var server = require("http").Server(app);
var io =  require('socket.io')(server);
server.listen(3000);
io.use(iosession);

io.on("connection",function (socket) {
  socket.on("enter", str=>{
    io.emit("reply",str);
  });

  socket.on("send", data=>{
    const user = socket.handshake.session.user;
    const loginname = user.loginname;
    const content = data;
    var nowDate = new Date();
    var doc = new Chatmes({
      loginname,
      content,
      createTime:nowDate,
      S_Time:date(nowDate,'-')
    });
    console.log(doc);
    socket.handshake.session.doc = doc;
    socket.handshake.session.save();
    // console.log("socket.handshake.session.doc=",socket.handshake.session.doc);
    io.emit("load",doc);
  });

});



// //导入session
// const session = require('express-session');
// const FileStore = require('session-file-store')(session);
//
// //创建 session 中间件
// const sessionMiddleware = session({
//   store:new FileStore(),   //本地文件储存，若无则以内存来存储
//   secret: 'keyboard cat',  //加密key
//   cookie: { maxAge: 600000 }  //本次请求和下次请求之间的时间（毫秒）
// });

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session);
// app.use(sessionMiddleware);

app.use(sassMiddleware({
  src: path.join(__dirname, 'public'),
  dest: path.join(__dirname, 'public'),
  indentedSyntax: true, // true = .sass and false = .scss
  sourceMap: true
}));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

// module.exports = app;
